#include "list_char.h"

LIST_CHAR* list_create()
{
	LIST_CHAR* aux = (LIST_CHAR*)malloc(sizeof(LIST_CHAR));
	aux->first = NULL;
	aux->last = NULL;
	aux->count = 0;
	return aux;
}

//Crea una lista a partir de un entero positivo
LIST_CHAR* list_create_from_int(int num)
{
	LIST_CHAR* list = list_create();

	//obtengo los dígitos
	int pow = 1;
	while(num != 0)
	{
		stack_add(list, (char) (num % 10 + '0'));
		num /= 10;
	}

	return list;
}

void stack_add(LIST_CHAR* list, char value)
{
	CHAR_NODE* new = (CHAR_NODE*)malloc(sizeof(CHAR_NODE));
	new->value = value;
	new->next = list->first;
	list->first = new;

	if(list->last == NULL)
	{
		list->last = new;
	}

	list->count++;
}

void list_add(LIST_CHAR* list, char value)
{
	CHAR_NODE* new = (CHAR_NODE*)malloc(sizeof(CHAR_NODE));
	new->value = value;
	new->next = NULL;

	if(list->last == NULL)
	{
		list->last = new;
		list->first = new;
	}
	else
	{
		list->last->next = new;
		list->last = new;
	}

	list->count++;
}
void list_kill(LIST_CHAR* list)
{
	CHAR_NODE* aux = list->first;
	while(aux != NULL)
	{
		CHAR_NODE* old = aux;
		aux = aux->next;
		free(old);
	}
	free(list);
}
void list_show(LIST_CHAR* list)
{
	CHAR_NODE* aux = list->first;
	while(aux != NULL)
	{
		printf("%c", aux->value);
		aux = aux->next;
	}
	printf("\n");
}

char* getString(LIST_CHAR* list)
{
	char* str = (char*)malloc(sizeof(char) * (list->count + 1));
	char* str_c = str;

	CHAR_NODE* aux = list->first;
	while(aux != NULL)
	{
		*str_c = aux->value;
		str_c++;
		aux = aux->next;
	}
	*str_c = '\0';

	return str;
}
